# -*- coding: utf-8 -*-
import traceback
from tkinter import *
from tkinter import filedialog, messagebox
from tkinter.ttk import Treeview
import time
import utils

LOG_LINE_NUM = 0


class MY_GUI():
    def __init__(self, init_window_name):
        self.init_window_name = init_window_name

    # 设置窗口
    def set_init_window(self):
        self.init_window_name.title("文件压缩工具_v1.0")
        self.init_window_name.geometry('1068x681+10+10')

        self.init_name_label = Label(self.init_window_name, text="输入姓名：")
        self.init_name_label.grid(row=0, column=0)
        name_content = StringVar()
        self.init_name_content = Entry(self.init_window_name, width=10, textvariable=name_content)
        self.init_name_content.grid(row=0, column=1, sticky=W)
        self.init_path_label = Label(self.init_window_name, text="文件路径：")
        self.init_path_label.grid(row=1, column=0)
        self.path_content = StringVar()
        self.path_content.set("点击文本框获取文件名路径...")
        self.init_path_content = Entry(self.init_window_name, width=40, textvariable=self.path_content)
        self.init_path_content.bind("<Button-1>", self.get_folder_path)
        self.init_path_content.grid(row=1, column=1, sticky=W)
        self.result_data_label = Label(self.init_window_name, text="输出结果")
        self.result_data_label.grid(row=0, column=12)
        self.log_label = Label(self.init_window_name, text="日志")
        self.log_label.grid(row=12, column=0)
        self.result_data_Text = Text(self.init_window_name, width=70, height=49)
        self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)
        self.log_data_Text = Text(self.init_window_name, width=66, height=9)
        self.log_data_Text.grid(row=13, column=0, columnspan=10)
        columns = ("文件名", "文件地址", "文件大小", "文件MD5")
        self.tree_date = Treeview(self.init_window_name, height=18, show="headings", columns=columns)
        self.tree_date.column("文件名", width=120, anchor='w')
        self.tree_date.column("文件地址", width=135, anchor='w')
        self.tree_date.column("文件大小", width=60, anchor='w')
        self.tree_date.column("文件MD5", width=150, anchor='w')

        self.tree_date.heading("文件名", text="文件名")
        self.tree_date.heading("文件地址", text="文件地址")
        self.tree_date.heading("文件大小", text="文件大小")
        self.tree_date.heading("文件MD5", text="文件MD5")
        self.tree_date.grid(row=2, column=0, rowspan=10, columnspan=10)
        VScroll1 = Scrollbar(self.init_window_name, orient='vertical', command=self.tree_date.yview)
        # VScroll1.place(relx=0.979, rely=0.190, relwidth=0.020, relheight=0.795)
        VScroll1.grid(row=2, column=10, sticky=W, rowspan=10, ipady=120)
        self.tree_date.configure(yscrollcommand=VScroll1.set)

        # 按钮
        self.str_trans_to_md5_button = Button(self.init_window_name, text="GO", bg="lightblue", width=7,
                                              command=lambda: self.btn_click(
                                                  self.path_content.get()))  # 调用内部方法  加()为直接调用
        self.str_trans_to_md5_button.grid(row=1, column=11)
        self.clean_button = Button(self.init_window_name, text="clean", bg="lightblue", width=7,
                                              command=lambda: self.clean_click())  # 调用内部方法  加()为直接调用
        self.clean_button.grid(row=2, column=11)

    def btn_click(self, path):
        name = self.init_name_content.get()
        if name == '':
            messagebox.showinfo('失败', '姓名或文件为空')
            return
        # 输出结果
        utils.info = {
            "归档人": self.init_name_content.get(),
            "归档时间": time.strftime('%Y-%m-%d', time.localtime(time.time())),
            "归档文件": utils.create_md5_info(self.init_path_content.get())
        }
        for i in utils.info:
            if isinstance(utils.info[i], list):
                self.result_data_Text.insert(END, i + ":\n" + '\n'.join(utils.info[i]) + "\n\n")
            else:
                self.result_data_Text.insert(END, i + ":" + utils.info[i] + "\n\n")
        self.result_data_Text.insert(END, "-----------------------------------------------------------")
        # 压缩文件
        try:
            utils.compressFolder(path)
            self.write_log_to_Text("备份文件成功！" + path + ".zip")
            utils.create_md5_file(path)
            self.write_log_to_Text("MD5生成成功！" + path + ".md5")
            utils.create_md5_file(path+'.zip')
            self.write_log_to_Text("MD5生成成功！" + path + ".zip.md5")
            self.log_data_Text.insert(END, "------------------------------------------")
        except Exception as e:
            self.write_log_to_Text(traceback.format_exc())

    def clean_click(self):
        utils.md5s = []
        utils.info = {}
        utils.folder_names = []
        self.path_content.set("点击文本框获取文件名路径...")
        self.init_path_content.config(state=NORMAL)
        self.init_name_content.config(state=NORMAL)

        x=self.tree_date.get_children()
        for item in x:
            self.tree_date.delete(item)
        

        





    def get_folder_path(self, f):
        name = self.init_name_content.get()
        if name == '':
            messagebox.showinfo('失败', '姓名或文件为空')
            return
        file_path = filedialog.askdirectory()  # 获取文件夹
        if file_path != '':
            file_path = file_path.replace('/', '\\')
            utils.get_file_info(file_path, self.tree_date, name)
            self.path_content.set(file_path)
            self.init_path_content.config(state=DISABLED)
            self.init_name_content.config(state=DISABLED)
        else:
            messagebox.showinfo('失败', '文件为空')

    # 功能函数

    # 日志动态打印
    def write_log_to_Text(self, logmsg):
        global LOG_LINE_NUM
        current_time = utils.get_current_time()
        logmsg_in = str(current_time) + " " + str(logmsg) + "\n"  # 换行
        if LOG_LINE_NUM <= 7:
            self.log_data_Text.insert(END, logmsg_in)
            LOG_LINE_NUM = LOG_LINE_NUM + 1
        else:
            self.log_data_Text.delete(1.0, 2.0)
            self.log_data_Text.insert(END, logmsg_in)


def gui_start():
    init_window = Tk()  # 实例化出一个父窗口
    ZMJ_PORTAL = MY_GUI(init_window)
    # 设置根窗口默认属性
    ZMJ_PORTAL.set_init_window()

    init_window.mainloop()  # 父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示


gui_start()
